﻿using System;
using System.Collections.Generic;
using _5E.Utils.TypeHelper.Extension;

namespace _5E.Utils.DbHelper.EasySQL
{
    /// <summary>
    /// 用于缓存生成EasyDbTable
    /// </summary>
    internal class EasyDbTableCache
    {
        #region 变量

        private const string NOT_EXIST_ATTRIBUTE_ERROR_MESSAGE_FORMAT = "{0}不包含EasySQLAttribute";

        private object m_Mutex = new object();

        private Dictionary<Type, EasyDbTable> m_Cache = new Dictionary<Type, EasyDbTable>();

        #endregion

        #region 实例方法

        public EasyDbTable GetEasyDbTable(Type type)
        {
            EasyDbTable easyDbTable;
            var notExist = !m_Cache.TryGetValue(type, out easyDbTable);
            if (notExist)
            {
                lock (m_Mutex)
                {
                    easyDbTable = CreateEasyDbTable(type);
                }
            }
            return easyDbTable;
        }

        private EasyDbTable CreateEasyDbTable(Type type)
        {
            var attribute = GetEasySQLAttribute(type);
            var easyDbTable = Parser.ParseMapping(attribute.MappingPath);
            return easyDbTable;
        }

        private EasySQLAttribute GetEasySQLAttribute(Type type)
        {
            EasySQLAttribute attribute;
            var hasAttribute = type.TryGetAttribute(out attribute);
            if (!hasAttribute)
            {
                var errorMessage = string.Format(NOT_EXIST_ATTRIBUTE_ERROR_MESSAGE_FORMAT, type.Name);
                throw new ArgumentNullException(errorMessage);
            }
            return attribute;
        }

        #endregion
    }
}
